﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TripsLogic.controller;
using TripsLogic.util;
using TripsLogic.WeSStatus;

namespace TripsLogic
{
    public partial class register : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                loadLang();
            }
        }

        private void loadLang()
        {
            chbTermPrivacy.Text = LangMsgController.getLngMsg("litTermPrivacy.Text", "Ved klik på 'opret profil' godkender du vores betingelser og takker ja til at prøve vores nyhedsbrev. Du kan altid framelde dig med ét klik.");
            litRetypePassword.Text = LangController.getLng("litRetypePassword.Text", "Retype password");
            litEmail.Text = LangController.getLng("litEmail.Text", "Email");
            litRegister.Text = lbtRegister.Text = this.Title = LangController.getLng("litRegister.Text", "Register");
            litPassword.Text = LangController.getLng("litPassword.Text", "Password");

            litFacebookRegister.Text = LangController.getLng("litFacebookLogin.Text", "Using Facebook to register");
            litFacebookRegisterContent.Text = LangMsgController.getLngMsg("litFacebookRegister.Text", "Registrer med ét klik. <br/><ul class='unstyled'>" + 
                "<li><i class='icon-ok'></i> Facebook login giver troværdighed til din medlemsprofil</li>" + 
                "<li><i class='icon-ok'></i> Vi skriver aldrig på din Wall uden at spørge først</li>" + 
                "<li><i class='icon-ok'></i> Vi overholder dine eksisterende indstillinger for privatliv</li>" + 
            "</ul>");

            this.reqValEmail.ErrorMessage = this.reqValPassword.ErrorMessage = this.reqValRePassword.ErrorMessage = LangController.getLng("litRequired.Text", "(*)");
            this.rgeValEmail.ErrorMessage = LangController.getLng("litInvalidFormat.Text", "Invalid format");
            this.cmpValRePassword.ErrorMessage = LangController.getLng("litMismatched.Text", " Mismatched");
            this.rgePasswordLength.ErrorMessage = this.rgeRePasswordLength.ErrorMessage = LangController.getLng("litPasswordLength.Text", "6 - 30 chars.");
        }

        protected void lbtRegister_Click(object sender, EventArgs e)
        {
            WeSSysUser.WeSSysUserClient client = new WeSSysUser.WeSSysUserClient();
            WeSSysUser.CreateAccountResult result = client.createAccountForActivating(txtEmail.Text, txtPassword.Text);
            registerResponse.Visible = true;
            contactform.Visible = false;
            if (result.sysUserResultStatus.statusCode == CreateAccountResult.STATUS_OK_CODE && result.id != "")
            {
                if (sendActivatingEmail(txtEmail.Text, txtPassword.Text, result.id))
                {
                    this.litRegisterResponse.Text = String.Format(LangMsgController.getLngMsg("litRegisterResponse.OK", "Thank you for registering account at <font style='font-weight:bold'>TripsLogic</font>.<br/>" +
                        "An email has been sent to <font style='font-weight:bold'><u>{0}</u></font>. Check your inbox and activate your account."), txtEmail.Text);
                    this.Title = LangController.getLng("litWebsiteTitle.Text", "TripsLogic") + " - " + LangController.getLng("litRegisterResponse.OK", "Register successfully");
                }
                else
                {
                    this.litRegisterResponse.Text = LangMsgController.getLngMsg("litRegisterResponse.Error", "Error occurs in registering progress.<br/>Please check again later.");
                    this.Title = LangController.getLng("litWebsiteTitle.Text", "TripsLogic") + " - " + LangController.getLng("litRegisterResponse.Error", "Error occurs in registering progress.");
                }
            }
            else
            {
                this.litRegisterResponse.Text = LangMsgController.getLngMsg("litRegisterResponse.Error", "Đã có lỗi xảy ra trong quá trình tạo tài khoản.<br/>Bạn vui lòng thử lại sau.");
                this.Title = LangController.getLng("litWebsiteTitle.Text", "TripsLogic") + " - " + LangController.getLng("litRegisterResponse.Error", "Error occurs in registering progress.");
            }
        }

        private bool sendActivatingEmail(string email, string password, string userId)
        {
            try
            {
                string activatedToken = Common.generateHash(txtEmail.Text);
                string activatedEmailTemplate = TemplateController.getTemplate("EMAIL_REGISTER_TEMP", "<p><font style='font-weight:bold'>TripsLogic</font> - Activate your account</p>" +
                        "<p><strong>Email:</strong> {0}</p>" +
                        "<p><strong>Password:</strong> {1}</p>" +
                        "<p>To activate your account at <font style='font-weight:bold'>TripsLogic</font>, please click the link below:<br/>{2}</p><br/>" +
                        "<p>This email has been sent from website <font style='font-weight:bold'>TripsLogic</font></p>" +
                        "<p><font style='font-weight:bold'>TripsLogic Team</font></p>");
                string activatedUrl = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf('/')) +
                    "/activate-account-" + userId + "-" + activatedToken;
                Common.sendEmail(txtEmail.Text, "", "", "", LangController.getLng("litActivatingEmail.Subject", "[TripsLogic] Activate account"),
                    String.Format(activatedEmailTemplate, email, "*****" + password.Substring(4), activatedUrl), "");
                return true;
            }
            catch (Exception ex)
            {
                // log
                //LogController.createLog(new Log(DateTime.Now.ToString("yyyyMMddHHmmss"), ex.Message, 1, "Error sendActivatingEmail"));
                return false;
            }
        }

        protected void txtEmail_TextChanged(object sender, EventArgs e)
        {
            string emailPattern = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
            if (System.Text.RegularExpressions.Regex.IsMatch(txtEmail.Text, emailPattern))
            {
                WeSSysUser.CheckAccountResult result = new WeSSysUser.WeSSysUserClient().checkAccount(txtEmail.Text);
                if (result.sysUserResultStatus.statusCode == CheckAccountResult.STATUS_AVAILABLE_CODE)
                {
                    this.lblIsAvailabelAccount.ForeColor = System.Drawing.Color.Green;
                    this.lblIsAvailabelAccount.Text = LangController.getLng("litAvailableAccount.Text", "Available");
                }
                else
                {
                    this.lblIsAvailabelAccount.ForeColor = System.Drawing.Color.Red;
                    this.lblIsAvailabelAccount.Text = LangController.getLng("litInAvailableAccount.Text", "Existed account");
                }
            }
            else
            {
                this.lblIsAvailabelAccount.ForeColor = System.Drawing.Color.Red;
                this.lblIsAvailabelAccount.Text = LangController.getLng("litInvalidFormat.Text", "Invalid format");
            }

            this.Title = LangController.getLng("litWebsiteTitle.Text", "TripsLogic") + " - " + this.lblIsAvailabelAccount.Text;
        }
    }
}